﻿using System;
using System.Data;
using Demo.BusinessLogic.Interface;
using Demo.Common.ExceptionHandlers;
using Demo.Common.ExceptionTypes;
using Demo.DataAccess.DataAccessHandler;

namespace Demo.BusinessLogic.Concrete
{
    public class SampleData : ISampleData
    {
        public DataTable GetUserList()
        {
            try
            {
                DataTable dt = SqlHandler.GetDataTable("GetUser");
                return dt;
            }
            catch (Exception ex)
            {
                bool rethrow = BusinessLogicExceptionHandler.HandleExcetion(ref ex);
                if (rethrow)
                {
                    throw ex;
                }
                return null;
            }
        }

        public DataTable GetUserData(string code)
        {
            try
            {
                object[] param = { code };
                DataTable dt = SqlHandler.GetDataTable("GetUserData", param);
                return dt;
            }
            catch (Exception ex)
            {
                bool rethrow = BusinessLogicExceptionHandler.HandleExcetion(ref ex);
                if (rethrow)
                {
                    throw ex;
                }
                return null;
            }
        }

        public int SomeCalculation(int a, int b)
        {
            try
            {
                int result = a / b;
                return result;
            }
            catch (Exception ex)
            {
                bool rethrow = BusinessLogicExceptionHandler.HandleExcetion(ref ex);
                if (rethrow)
                {
                    throw ex;
                }
                return 0;
            }
        }

        public void SaveData(string Usercode, int amount)
        {
            try
            {
                object[] param = { Usercode };
                DataTable dt = SqlHandler.GetDataTable("GetUserData", param);

                int balance = (int)dt.Rows[0].ItemArray[2];
                int limit = (int)dt.Rows[0].ItemArray[3];
                if ((balance + amount) > limit)
                {
                    BusinessLogicCustomException ex = new BusinessLogicCustomException("Limit excceeded. Data cannot be saved.");
                    throw ex;
                }
                else
                {
                    // invoice approved flow.
                }
            }
            catch (Exception ex)
            {
                bool rethrow = BusinessLogicExceptionHandler.HandleExcetion(ref ex);
                if (rethrow)
                {
                    throw ex;
                }
            }
        }
    }
}